<template>
  <t-layout>
    <t-aside v-show="asideVisible">
      <t-layout style="margin: 0 10px">
        <t-content>
          <t-space direction="vertical" style="width: 100%; height: 500px">
            <t-collapse default-expand-all="true">
              <t-collapse-panel value="1" header="">
                <template #expandIcon><t-icon name="list" /></template>
                <div class="usepanel">
                  <t-tree
                    ref="tree"
                    @active="treeActive"
                    @expand="treeExpand"
                    activable
                    hover
                    expand-all
                    transition
                    max-height="450"
                  />
                </div>
              </t-collapse-panel>
            </t-collapse>
          </t-space>
        </t-content>
        <t-footer style="margin: 10px">
          <t-button theme="default" variant="text" @click="asideVisible = false"
            ><t-icon name="file-1"
          /></t-button>
        </t-footer>
      </t-layout>
    </t-aside>

    <t-content>
      <div @contextmenu="rightClicked($event)" style="width: 100%; height: 500px">
        <div class="tabs">
          <button class="tab" @click="openTab($event, 'tab1')">markdown</button>
          <button class="tab" @click="openTab($event, 'tab2')">html</button>
          <button class="tab" @click="openTab($event, 'tab3')">text</button>
          <button class="tab" @click="openTab($event, 'tab4')">代码</button>
          <button class="tab" @click="openTab($event, 'tab5')">浏览</button>
        </div>

        <div id="tab1" class="tabcontent">
          <div id="vditor"></div>
        </div>

        <div id="tab2" class="tabcontent">
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="wangeRef"
              :defaultConfig="wangTolConf"
              :mode="wangmode"
            />
            <Editor
              style="height: 450px; overflow-y: hidden"
              v-model="wanghtml"
              :defaultConfig="wangConfig"
              :mode="wangmode"
              @onCreated="handleCreated"
            />
          </div>
        </div>

        <div id="tab3" class="tabcontent">
          <div style="width: 100%; height: 500px">
            <t-textarea autosize allowInputOverMax v-model="textdata" placeholder="请输入内容" />
          </div>
        </div>
        <div id="tab4" class="tabcontent">
          <t-textarea autosize allowInputOverMax v-model="wanghtml" placeholder="请输入内容" />
        </div>
        <div id="tab5" class="tabcontent">
          <div v-html="markhtml"></div>
        </div>
      </div>
    </t-content>
  </t-layout>
  <div v-show="menuVis" class="contmenu">
    <input ref="importFile" @change="importFileChange($event)" type="file" v-show="false" />
    <ul>
      <li @click.stop="fopen"><t-icon name="file" /><span>打开文件</span></li>
      <li @click.stop="fsave"><t-icon name="save" /><span>保存文件</span></li>
      <li class="has-submenu">
        <t-icon name="file-export" /><span>另存文件</span>
        <ul class="submenu">
          <li @click.stop="saveAs('txt')"><t-icon name="file" /><span>TXT文件</span></li>
          <li @click.stop="saveAs('md')"><t-icon name="file" /><span>MD文件</span></li>
          <li @click.stop="saveAs('html')"><t-icon name="file" /><span>网页文件</span></li>
        </ul>
      </li>
      <li @click.stop="parsing"><t-icon name="file-1" /><span>解析文件</span></li>
    </ul>
  </div>
  <t-dialog v-model:visible="saveVis" :closeBtn="false" :on-confirm="onConfirmSave" header="另存为">
    <t-input v-model="saveFile.name" placeholder="请输入文件名" />
  </t-dialog>
</template>
<script setup>
import { onMounted, onBeforeUnmount, ref, shallowRef, watch, reactive } from 'vue'
import Vditor from 'vditor'
import 'vditor/dist/index.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import mammoth from 'mammoth'
import { marked } from 'marked'

const markdata = ref('')
const wanghtml = ref('<p>hello</p>') //tab2和tab4内容
const textdata = ref('') //tab3内容
const markhtml = ref('') //tab5内容

///wangeditor
const wangTolConf = {}
const wangConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      fieldName: 'file', // form-data fieldName ，默认值 'wangeditor-uploaded-image'
      server: 'http://localhost:3000/api/upload?scene=wangeditor',
      base64LimitSize: 5 * 1024 // 5kb, 小于该值就插入 base64 格式（而不上传），默认为 0
    }
  }
}
const wangeRef = shallowRef()
const handleCreated = (editor) => {
  wangeRef.value = editor // 记录 editor 实例，重要！
}
const wangmode = ref('default') // 或 'simple'

//vditor
var vditor = null
watch(
  markdata,
  (content) => {
    if (vditor) vditor.setValue(content)
  },
  { immediate: true }
)
onMounted(() => {
  vditor = new Vditor('vditor', {
    height: 460,
    mode: 'wysiwyg'
  })
})
// 销毁
onBeforeUnmount(() => {
  if (vditor != null) vditor.destroy()
  const editor = wangeRef.value
  if (editor == null) return
  editor.destroy()
})
/**********
 * 数据解析
 * *******/
let fmarkdata
var origFileName
const importFileChange = (event) => {
  var file = event.target.files[0]
  origFileName = file.name
  saveFile.name = origFileName.substring(0, origFileName.lastIndexOf('.'))
  saveFile.type = origFileName.match(/[^.]+$/)[0]
  var reader = new FileReader()

  reader.onload = function (loadEvent) {
    var arrayBuffer = loadEvent.target.result
    mammoth
      .convertToMarkdown({ arrayBuffer: arrayBuffer })
      .then((result) => {
        fmarkdata = result.value
        markdata.value = fmarkdata
      })
      .done()
  }
  reader.readAsArrayBuffer(file)
}
const parsing = function () {
  asideVisible.value = true
  let compile = { label: '全文', value: 1, content: fmarkdata }
  tree.value.appendTo(compile)
  ParsingContent(fmarkdata, 1, 1)
}
const ParsingContent = function (compile, id, level) {
  console.log('id:' + id + ' level:' + level)
  let reg = regex(level)
  if (!reg.test(compile)) return
  var sections = compile.split(reg)

  sections.forEach((item, index) => {
    const found = item.match(/([\w|\x20|\u4e00-\u9fa5]*?)\n/)
    item = item.replace(found[0], '')
    let value = id * 10 + index
    console.log('level:' + level + ' new id:' + value + ' found[1]:' + found[1])
    if (found[1] == '') found[1] = '引言'
    let data = { label: found[1], value: value, content: item }
    tree.value.appendTo(id, data)
    ParsingContent(item, value, level + 1)
  })
}
const regex = (level) => {
  let sReg = new RegExp('\\s#{' + level + '}\\s', 'g')
  return sReg
}
const download = (name) => {
  var suffix = name.substring(name.lastIndexOf('.') + 1)
  var type, data
  if (suffix == 'txt') {
    type = 'text/plain;charset=utf-8'
    data = textdata.value
  } else if (suffix == 'json') {
    type = 'application/json'
  } else if (suffix == 'md') {
    type = 'text/markdown'
    data = markdata.value
  } else if (suffix == 'html') {
    type = 'application/xhtml+xml'
    data = wanghtml.value
  } else {
    alert('不能保存' + suffix + '类型的文件！')
    return
  }
  const blob = new Blob([data], { type: type })
  const objectURL = URL.createObjectURL(blob)
  const aTag = document.createElement('a')
  aTag.href = objectURL
  aTag.download = name
  aTag.click()
  URL.revokeObjectURL(objectURL)
}

//
//侧边栏和树形控件
////
const asideVisible = ref(false)
const tree = ref()
const treeExpand = (value) => {
  console.log('onExpand' + value)
}
const treeActive = (value, context) => {
  console.log(context.node.data.content)
  markdata.value = context.node.data.content
  alert(value)
}
/////////
//选项卡
///////////
const openTab = (evt, tabName) => {
  var i, tabcontent, tablinks
  tabcontent = document.querySelectorAll('.tabcontent')
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = 'none'
  }
  tablinks = document.querySelectorAll('.tab')
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(' active', '')
  }
  document.querySelector('#' + tabName).style.display = 'block'
  evt.currentTarget.className += ' active'
  if (tabName == 'tab5') markhtml.value = marked(vditor.getValue())
}
//右键菜单
////////
let menuVis = ref(false)
const rightClicked = (e) => {
  e.preventDefault()
  menuVis.value = true
  let myMenu = document.querySelector('.contmenu')
  myMenu.style.top = `${e.clientY}px`
  myMenu.style.left = `${e.clientX}px`
}
document.addEventListener('click', () => {
  menuVis.value = false
})

//
const importFile = ref()
function fopen() {
  importFile.value.click()
  menuVis.value = false
}
const saveVis = ref(false)
const saveFile = reactive({
  name: '',
  type: 'txt'
})
const onConfirmSave = () => {
  saveVis.value = false
  download(saveFile.name + '.' + saveFile.type)
}
function saveAs(type) {
  saveFile.type = type
  saveVis.value = true
  menuVis.value = false
}
function fsave() {
  download(origFileName)
  menuVis.value = false
}
//
</script>

<style lang="less">
.usepanel {
  margin-left: -30px;
}
/* Style the tab */
.tabs {
  background-color: #fffefe;
  border: 1px solid #eee;
}
.tab {
  padding: 10px;
  border: none;
  outline: none;
  cursor: pointer;
  font-size: 15px;
  background-color: #fefefe;
}
.tab:hover {
  background-color: #f8f8f8;
}
.tabcontent {
  display: none;
  padding: 6px 12px;
  height: 100%;
  border: 1px solid #ccc;
  border-top: none;
}
/* Style the contextmenu */
.contmenu {
  background-color: #f9f9f9;
  border: 1px solid #ccc;
  list-style-type: none;
  position: fixed;
  padding: 0;
  margin: 0;
}

.contmenu li {
  position: relative;
  padding: 5px 10px;
  cursor: pointer;
}
.contmenu li span {
  padding: 1px 10px;
  font-size: 12px;
}
.contmenu li:hover {
  background-color: #eee;
}

.submenu {
  display: none;
  position: absolute;
  list-style-type: none;
  background-color: #f9f9f9;
  border: 1px solid #ccc;
  padding: 0;
  left: 100%;
  top: 0;
}
.submenu li {
  width: 100px;
  margin: 0;
  padding: 2px 0 0 10px;
}
.contmenu li:hover > .submenu {
  display: block;
}
li.has-submenu:after {
  content: '\25bc'; /*这是一个倒三角▼*/
  font-size: 0.7em;
  padding-left: 5px;
  vertical-align: middle;
}

li.has-submenu:hover:after {
  content: '\25b2';
}
</style>
